package filter

import (
	"github.com/project-flogo/core/data"
	"fmt"

	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/mapper"
	"github.com/project-flogo/core/data/resolve"
)

type Filter interface {
	Apply(data map[string]interface{}) bool
}

type filter struct {
	m mapper.Mapper
}

func NewFilter(expr string) (*filter, error) {
	f := mapper.NewFactory(resolve.GetBasicResolver())
	m, err := f.NewMapper(map[string]interface{}{
		"filter": expr,
	})
	if err != nil {
		return nil, err
	}
	fp := filter{
		m: m,
	}
	return &fp, nil
}

func (f *filter) Apply(values map[string]interface{}) bool {
	scope := data.NewSimpleScope(values, nil)
	result, err := f.m.Apply(scope)
	if err != nil {
		return false
	}
	fmt.Printf("result = %+v\n", result)
	cond, err := coerce.ToBool(result["filter"])
	if err != nil {
		return false
	}
	return cond
}
